//
//  QHHCPConfig.m
//  MUGH
//
//  Created by 李志良的mac mini on 2020/3/30.
//  Copyright © 2020 MUGH. All rights reserved.
//

#import "QHHCPConfig.h"
#import "QHHCPInternalPreferences.h"


@implementation QHHCPConfig
+ (id)configFromBundle:(NSString*)folderName fileName:(NSString *)configFileName {
    
    NSString * configFilePath = [NSString stringWithFormat:@"www/%@",configFileName];
    NSURL *wwwFolderURL = [NSURL fileURLWithPath:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:folderName] isDirectory:YES];
    NSURL *chcpJsonFileURLFromBundle = [wwwFolderURL URLByAppendingPathComponent:configFilePath];
    
    NSData *jsonData = [NSData dataWithContentsOfURL:chcpJsonFileURLFromBundle];
    if (jsonData == nil) {
        return nil;
    }
    
    NSError *error = nil;
    id json = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
    if (error) {
        DeBugLog(@"Can't read application config from bundle.");
        return nil;
    }
    
    return json;
}

//读取最新文件夹chcp.json内容
+ (id)configFromLocalWithFolderName:(NSString*)folderName fileName:(NSString *)configFileName{
    QHHCPInternalPreferences * hcpPreferences = [QHHCPInternalPreferences loadFromUserDefaultsWithFolderName:folderName];
    // 获取Document目录
    NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDirectory = [paths lastObject];
    NSString *configFilePath = [docDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@/www",folderName,hcpPreferences.currentReleaseVersionName]];
    DeBugLog(@"%@",configFilePath);
    
    NSURL *wwwFolderURL = [NSURL fileURLWithPath:configFilePath isDirectory:YES];
    NSURL *chcpJsonFileURLFromBundle = [wwwFolderURL URLByAppendingPathComponent:configFileName];
    
    NSData *jsonData = [NSData dataWithContentsOfURL:chcpJsonFileURLFromBundle];
    if (jsonData == nil) {
        return nil;
    }
    
    NSError *error = nil;
    id json = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
    if (error) {
        DeBugLog(@"Can't read application config from bundle.");
        return nil;
    }
    
    return json;
}

+(NSString*)wwwFolderAbsolutePathWithContentFolderName:(NSString*)folderName{
    NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDirectory = [paths lastObject];
    NSString *configFilePath = [docDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/www",folderName]];
    return configFilePath;
}

@end
